<!--
 * @Descripttion:
 * @Author: caijj
 * @Date: 2020-11-05 15:49:02
 * @LastEditors: caijj
 * @LastEditTime: 2020-12-24 17:21:56
-->
<template>
  <div>
    <el-upload
      ref="upload"
      class="upload-demo"
      :accept="accept"
      action="/"
      :headers="headers"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :before-remove="beforeRemove"
      :limit="1"
      :on-exceed="handleExceed"
      :file-list="fileList"
      :auto-upload="false"
    >
      <el-link v-show="fileList.length===0" slot="trigger" type="primary" class="control" :underline="false">上传文件</el-link>
    </el-upload>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth';

export default {
  props: {
    filePath: {
      type: String,
      default: ''
    },
    fileSize: {
      type: Number,
      default: 2
    },
    isView: {
      type: Boolean,
      default: false
    },
    accept: {
      type: String,
      default: '.csv, .xlsx, , .xls'
    }
  },
  data() {
    return {
      fileList: [],
      headers: { token: '' }
    };
  },
  mounted() {
    this.headers.token = getToken();
  },
  methods: {
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.$emit('onSuccess', file);
    },
    delFile() {
      this.$refs.upload.clearFiles();
      this.fileList = [];
      this.$emit('onSuccess', this.fileList);
    },
    handleChange(file, fileList) {
      const fileName = file.name.split('.');
      const len = fileName.length - 1;
      const isXLSX = fileName[len] === 'xlsx' ||
            fileName[len] === 'xls' ||
            fileName[len] === 'xltx' ||
            fileName[len] === 'xlt' ||
            fileName[len] === 'xlsm' ||
            fileName[len] === 'xlsb' ||
            fileName[len] === 'xltm' ||
            fileName[len] === 'csv';
      const isNormalSize = file.size / 1024 / 1024 < this.fileSize;

      if (!isXLSX) {
        this.$message.error('上传文件只能是xls或xlsx（即Excel格式）格式!');
        this.delFile();
        return;
      }
      if (!isNormalSize) {
        this.$message.error(`上传文件大小不能超过${this.fileSize}MB!`);
        this.delFile();
        return;
      }
      if (fileList.length > 0) {
        this.fileList = fileList;
        this.$emit('onSuccess', this.fileList);
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning('当前限制选择 1 个文件');
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    }
  }
};
</script>

<style>
  .el-upload__tip {
    color: red;
  }
  .upload-demo{
    display: flex;
    align-items: center;
  }
  .control{
    font-size: 12px;
    padding-right: 10px;
  }
</style>
